package com.efast.cafe.commponent.es.tcp.coder;

import java.util.List;

import com.efast.cafe.commponent.es.tcp.bean.TcpData;
import com.efast.cafe.commponent.es.tcp.utils.BytesHexStrTranslate;
import com.efast.cafe.commponent.log.ext.CafeLogger;
import com.efast.cafe.commponent.log.ext.CafeLoggerFactory;

import ch.qos.logback.classic.Logger;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

public class ByteToMessageDecoder extends MessageToMessageDecoder<ByteBuf>{
	//头（1） + 版本 (1) + 命令 (4) + 承载内容长度(2)  = 8
	private static final int HEADER_SIZE = 8;  
	CafeLogger logger = CafeLoggerFactory.getLogger(getClass());
	
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		int allLength = in.readableBytes();
        if (allLength < HEADER_SIZE) {  
        	ByteBuf buf = in.readBytes(in.readableBytes());  
            byte[] req = new byte[buf.readableBytes()];
            buf.readBytes(req);
            in.skipBytes(in.readableBytes());       
            return;
        }else{
        	try{
        		StringBuilder hexStr = new StringBuilder(); 
                //注意在读的过程中，readIndex的指针也在移动  
                 
        		 //协议版本
                 byte ver = in.readByte();
                 String tyteStr = Integer.toHexString(ver & 0xFF);
                 if (tyteStr.length() == 1) {  
                 	tyteStr = '0' + tyteStr;  
                 } 
                 hexStr.append(tyteStr);
                 
                 //协议命令
                 byte command[] = {in.readByte(),in.readByte(),in.readByte(),in.readByte()};
                 String commandStr = new String(command,"utf-8");
                 hexStr.append(BytesHexStrTranslate.bytesToHexFun1(command));
                 
                 //读取承载内容长度
                 byte lengths[] = {in.readByte(),in.readByte()};
                 int length = BytesHexStrTranslate.bytesToInt2(lengths, 0);
                 hexStr.append(BytesHexStrTranslate.bytesToHexFun1(lengths));
                 

                 StringBuilder contentStr = new StringBuilder();
                 //内容
                 for(int i=0;i<length;i++){
                	 byte cont = in.readByte();
                	 String conthex = Integer.toHexString(cont & 0xFF);  
                	 if (conthex.length() == 1) {  
                		 conthex = '0' + conthex;  
                      } 
                	 contentStr.append(conthex);
                 }
                 
                 String cs = contentStr.toString().toLowerCase().replaceAll("5e5d", "5e").replaceAll("5e7d", "7e");
                 hexStr.append(cs);
                 
                 //协议内容
                 byte[] cb = BytesHexStrTranslate.toBytes(cs);
      
                // String crc = Integer.toHexString(CRC16.CRC_XModem(BytesHexStrTranslate.toBytes(hexStr.toString())));
               //  System.out.println("crc:"+crc);
                 
                 //crc code
                 byte[] crcbyte = {in.readByte(),in.readByte()};
                 String crcCode = BytesHexStrTranslate.bytesToHexFun1(crcbyte);
                 
                 hexStr.append(crcCode);
                 
                 TcpData data = new TcpData();
                 data.setVersion(ver);
                 data.setContent(cb);
                 data.setHexStr(hexStr.toString());
                 data.setCommand(commandStr);
                 out.add(data);
                 logger.info(hexStr.toString());
        	}catch(Exception e){
        		System.out.println("解析数据出错,"+e.getMessage());
        	}
        }
	}

}
